//
//  SearchViewController.m
//  MountEverestFM
//
//  Created by ChenNing on 15/11/5.
//  Copyright © 2015年 chenn. All rights reserved.
//

#import "SearchViewController.h"
#import "CommonSearchTableViewCell.h"
#import "SearchHistoryModel.h"
#import "HistorySearchTableViewCell.h"
#import "FMsearchXiangViewController.h"
@interface SearchViewController ()<UISearchBarDelegate,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic ,strong)UISearchBar *searchBar;
@property (nonatomic ,strong)UIScrollView *scrollView;
@property (nonatomic ,strong)UITableView *tableView;

@property (nonatomic ,strong)NSArray *commonSearchArr;
@property (nonatomic,strong)NSMutableArray *hisrotyArr;
@end

@implementation SearchViewController



- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    self.searchBar=[[UISearchBar alloc]init];
    self.searchBar.barStyle=UIBarStyleDefault;
    self.searchBar.placeholder=@"搜索";
    
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(quxiao:)];
    
    self.navigationItem.titleView =self.searchBar;
    self.searchBar.delegate=self;

    self.tableView= [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = UIColorFromRGB(0xe7e7e7);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.view addSubview:self.tableView];
    
    
    [self selectHistory];
    [self getCommonSearch];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.commonSearchArr.count != 0 && self.hisrotyArr.count != 0) {
        return 2;
    }else{
        if (self.commonSearchArr.count != 0 || self.hisrotyArr.count != 0) {
            return 1;
        }
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return FM_Screen_Pts_Height*50;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.hisrotyArr.count != 0 && self.commonSearchArr.count !=0) {
        if (section == 0) {
            // 历史
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FM_Screen_Width, FM_Screen_Pts_Height*50)];
            view.backgroundColor = [UIColor whiteColor];
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(FM_Screen_Pts_Width*30, 0, FM_Screen_Pts_Width*100, FM_Screen_Pts_Height*50)];
            titleLabel.text = @"历史记录";
            titleLabel.textColor = [UIColor grayColor];
            titleLabel.font = [UIFont systemFontOfSize:15];
            [view addSubview:titleLabel];
            
            
            UIButton *clearButton=[UIButton buttonWithType:UIButtonTypeSystem];
            clearButton.frame = CGRectMake(FM_Screen_Width-FM_Screen_Pts_Width*110, 0, FM_Screen_Pts_Width*100, FM_Screen_Pts_Height*50);
            [clearButton setTitle:@"清空记录" forState:UIControlStateNormal];
            [clearButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [clearButton addTarget:self action:@selector(clearButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:clearButton];
            
            return view;
        }else{
            // 推荐
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FM_Screen_Width, FM_Screen_Pts_Height*50)];
            view.backgroundColor = [UIColor whiteColor];
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(FM_Screen_Pts_Width*30, 0, FM_Screen_Pts_Width*100, FM_Screen_Pts_Height*50)];
            titleLabel.text = @"大家都在搜";
            titleLabel.textColor = [UIColor grayColor];
            titleLabel.font = [UIFont systemFontOfSize:15];
            [view addSubview:titleLabel];
            return view;
        }
    }else{
        if (self.hisrotyArr.count != 0) {
            // 历史
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FM_Screen_Width, FM_Screen_Pts_Height*50)];
            view.backgroundColor = [UIColor whiteColor];
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(FM_Screen_Pts_Width*30, 0, FM_Screen_Pts_Width*100, FM_Screen_Pts_Height*50)];
            titleLabel.text = @"历史记录";
            titleLabel.textColor = [UIColor grayColor];
            titleLabel.font = [UIFont systemFontOfSize:15];
            [view addSubview:titleLabel];
            
            UIButton *clearButton=[UIButton buttonWithType:UIButtonTypeSystem];
            clearButton.frame = CGRectMake(FM_Screen_Width-FM_Screen_Pts_Width*110, 0, FM_Screen_Pts_Width*100, FM_Screen_Pts_Height*50);
            [clearButton setTitle:@"清空记录" forState:UIControlStateNormal];
            [clearButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [clearButton addTarget:self action:@selector(clearButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:clearButton];
            
            return view;
        }
        if (self.commonSearchArr.count != 0) {
            // 推荐
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FM_Screen_Width, FM_Screen_Pts_Height*50)];
            view.backgroundColor = [UIColor whiteColor];
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(FM_Screen_Pts_Width*30, 0, FM_Screen_Pts_Width*100, FM_Screen_Pts_Height*50)];
            titleLabel.text = @"大家都在搜";
            titleLabel.textColor = [UIColor grayColor];
            titleLabel.font = [UIFont systemFontOfSize:15];
            [view addSubview:titleLabel];
            return view;
        }
    }
    return [[UIView alloc] initWithFrame:CGRectZero];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return FM_Screen_Pts_Height*15;
    }
    return 0.00001f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section==0) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, FM_Screen_Width, FM_Screen_Pts_Height*15)];
        view.backgroundColor = UIColorFromRGB(0xe7e7e7);
        return view;
    }
    return [[UIView alloc]initWithFrame:CGRectZero];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.commonSearchArr.count != 0 && self.hisrotyArr.count != 0) {
        if (indexPath.section==0) {
            HistorySearchTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sousuo1"];
            if (!cell) {
                cell=[[HistorySearchTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"sousuo1"];
            }
            cell.arr = self.hisrotyArr;
            void(^blocklao1)(NSString *str)=^(NSString *str){
                FMsearchXiangViewController *xiang=[[FMsearchXiangViewController alloc]init];
                xiang.str=str;
                [self.navigationController pushViewController:xiang animated:YES];
            };
            cell.block=blocklao1;
            return cell;
        }else{
            CommonSearchTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sousuo"];
            if (!cell) {
                cell=[[CommonSearchTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"sousuo"];
            }
            cell.arr = self.commonSearchArr;
            void(^blocklao1)(NSString *str)=^(NSString *str){
                FMsearchXiangViewController *xiang=[[FMsearchXiangViewController alloc]init];
                xiang.str=str;
                [self.navigationController pushViewController:xiang animated:YES];
            };
            cell.block=blocklao1;
            return cell;
        }
    }else{
        if (self.hisrotyArr.count != 0 ){
            HistorySearchTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sousuo1"];
            if (!cell) {
                cell=[[HistorySearchTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"sousuo1"];
            }
            cell.arr = self.hisrotyArr;
            void(^blocklao1)(NSString *str)=^(NSString *str){
                FMsearchXiangViewController *xiang=[[FMsearchXiangViewController alloc]init];
                xiang.str=str;
                [self.navigationController pushViewController:xiang animated:YES];
            };
            cell.block=blocklao1;
            return cell;
        }
        if(self.commonSearchArr.count != 0) {
            CommonSearchTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"sousuo"];
            if (!cell) {
                cell=[[CommonSearchTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"sousuo"];
            }
            cell.arr = self.commonSearchArr;
            void(^blocklao1)(NSString *str)=^(NSString *str){
                FMsearchXiangViewController *xiang=[[FMsearchXiangViewController alloc]init];
                xiang.str=str;
                [self.navigationController pushViewController:xiang animated:YES];
            };
            cell.block=blocklao1;
            return cell;
        }
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.commonSearchArr.count != 0 && self.hisrotyArr.count != 0) {
        if (indexPath.section==0) {
            return  round(self.hisrotyArr.count/3)*FM_Screen_Pts_Height*60+FM_Screen_Pts_Height*60;
        }
        else
        {
            return round(self.commonSearchArr.count/3)*FM_Screen_Pts_Height*70;
        }
    }else{
        if (self.commonSearchArr.count != 0 ){
            return round(self.commonSearchArr.count/3)*FM_Screen_Pts_Height*40+FM_Screen_Pts_Height*10;
        }
        if(self.hisrotyArr.count != 0) {
            return round(self.hisrotyArr.count/3)*FM_Screen_Pts_Height*40+FM_Screen_Pts_Height*10;
        }
    }
    return 0;
}

-(void)clearButtonAction:(UIButton *)sender
{
    DBHandler *db=[DBHandler shareInstance];
    [db openDB];
    [db deleteSearch:self.hisrotyArr];
    [self.hisrotyArr removeAllObjects];
    [self.tableView reloadData];
}

//取消按钮
-(void)quxiao:(UIBarButtonItem *)qu
{
     [self.searchBar resignFirstResponder];
}

//搜索
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    SearchHistoryModel *searchHistory = [SearchHistoryModel collectModelWithStr:searchBar.text];
    DBHandler *db = [DBHandler shareInstance];
    [db openDB];
    [db insertSearch:searchHistory];
    [db closeDB];
    
    [self.hisrotyArr addObject:searchHistory];
//    [self.tableView reloadData];
    FMsearchXiangViewController *xiang=[[FMsearchXiangViewController alloc]init];
    xiang.str=searchBar.text;
    [self.navigationController pushViewController:xiang animated:YES];
    
}
//搜索响应
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    [self.tableView reloadData];
    [self.searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 查询历史记录
- (void)selectHistory
{
    self.hisrotyArr = [NSMutableArray array];
    DBHandler *db=[DBHandler shareInstance];
    [db openDB];
    self.hisrotyArr = [db selectAllSearch];
}

// 获取都在搜索的数据
-(void)getCommonSearch
{
    self.commonSearchArr = [NSMutableArray array];
    [NetWorkManager GET:@"http://mobile.ximalaya.com/m/hot_search_keys?device=iPhone" isCaChe:YES resultData:^(id responseObject) {
        self.commonSearchArr=[responseObject objectForKey:@"keys"];
        [self.tableView reloadData];
    } resultRrror:^(NSError *error) {
        
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.tableView reloadData];
}

@end
